import axios from "axios";
import config from './config.js';
import { UniAdapter } from "uniapp-axios-adapter";

const timeoutSet = 10000 // 配置超时时间
// 创建axios实例
const request = axios.create({
  baseURL: config.baseUrl,
  timeout: timeoutSet, // 基础超时时间
  adapter: UniAdapter,
});
const baseURL = '/at/AAS-aas';

// 请求拦截器
request.interceptors.request.use((config) => {
  config.headers["Authorization"] = "token";
  config.data = {
	...config.data,
    body: 'test',
    signkey: 'test',
    apphead: 'test'
  };
  return config;
});

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      const { data } = response;
      return data.code === 200 ? Promise.resolve(data) : Promise.reject(data);
    }
    return Promise.reject(new Error(`HTTP错误：${response.status}`));
  },
  (error) => {
    let errorMsg = "网络异常，请稍后重试";
    if (axios.isCancel(error)) {
      errorMsg = "请求已取消";
    } else if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
      errorMsg = "请求超时，请稍后重试";
    }
    error.customMsg = errorMsg;
    return Promise.reject(error);
  }
);

/**
 * 核心请求封装
 * @param {Object} options - 请求配置
 * @returns {Promise}
 */
function requestOption(options) {
 console.log(options,'传递的参数2')
  const { 
    showLoading = false, 
    timeout = timeoutSet,
    ...restOptions 
  } = options;

  let isLoadingClosed = false;
  let timeoutTimer = null;
  const cancelSource = axios.CancelToken.source();

  // 统一关闭loading的函数
  const closeLoading = () => {
    if (showLoading && !isLoadingClosed) {
      uni.hideLoading();
      isLoadingClosed = true;
    }
  };

  // 显示loading
  if (showLoading) {
    uni.showLoading({
      title: '加载中...',
      mask: true
    });
  }

  return new Promise((resolve, reject) => {
    // 手动超时定时器 
    timeoutTimer = setTimeout(() => {
      // 主动取消请求
      cancelSource.cancel("请求超时");
      // 关闭loading
      closeLoading();
      // 在Promise作用域内使用reject
      reject(new Error("请求超时，请稍后重试"));
    }, timeout);

    // 发起请求
    request({
      ...restOptions,
      url: `${baseURL}/${restOptions.url}`,
      cancelToken: cancelSource.token,
      timeout: timeout,
    })
    .then((res) => {
      closeLoading();
      clearTimeout(timeoutTimer);
      resolve(res.data);
    })
    .catch((err) => {
      closeLoading();
      clearTimeout(timeoutTimer);
      const errMsg = err.customMsg || err.message || "网络异常，请稍后重试";
      uni.showToast({
        title: errMsg,
        icon: "none",
        duration: 2000
      });
      reject(err);
    });
  });
}

export default requestOption;
    